How to calculate the difference between Two Dates in C#?
How to calculate the difference between Two Dates in C#?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Ravi Vishwakarma
10-Jun-2024You can calculate the difference between two dates using the
DateTime
structure and its associated methods. TheDateTime
structure has aSubtract
the method that returns aTimeSpan
object representing the difference between twoDateTime
instances. TheTimeSpan
object provides properties to get the difference in days, hours, minutes, seconds, and more.Here’s how you can calculate the difference between two dates:
Example -
Explanation
Create
DateTime
Instances: CreateDateTime
instances for the start date and end date. You can use theDateTime
constructor to create specific dates or use properties likeDateTime.Now
for the current date and time.Calculate the Difference: Subtract the start date from the end date using the
-
operator or theSubtract
method. This returns aTimeSpan
object.Access
TimeSpan
Properties: Use properties of theTimeSpan
object to get the difference in various units:Days
: Gets the total number of whole days.TotalHours
: Gets the total number of hours, including fractional hours.TotalMinutes
: Gets the total number of minutes, including fractional minutes.TotalSeconds
: Gets the total number of seconds, including fractional seconds.Read more: DateTime shorting in C#